/**
 * Title:ImageLoader
 * Description:TODO
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:maple
 * Date:2014/8/8
 * Version 1.0
 */
package com.nostra13.universalimageloader.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;


import java.io.File;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.FileConstants;

/**
 * Created with Android Studio. Title:ImageLoader
 * Description: Author:zc Date:2014/8/8
 * Time:19:10
 */
public class ImageLoaderUtil {

    public static void loadImage(Context c, ImageView iv, String imageUrl,
                                 int errorBgRes) {
        loadImage(c, iv, imageUrl, errorBgRes, errorBgRes);
    }

    public static void loadImage(Context c, ImageView iv, String imageUrl,
                                 int errorBgRes, int defaultBgRes) {
        DisplayImageOptions options = getImageOptionsPress(errorBgRes,
                defaultBgRes);
        ImageLoader loader = getImageLoader(c);
        if (loader != null)
            loader.displayImage(imageUrl, iv, options);
    }

    public static void loadImage(Context c, ImageView iv, String imageUrl,
                                 DisplayImageOptions option) {
        DisplayImageOptions options = option;
        ImageLoader loader = getImageLoader(c);
        loader.displayImage(imageUrl, iv, options);
    }

    public static ImageLoader getImageLoader(Context c) {
        ImageLoader loader = ImageLoader.getInstance();
        if (!loader.isInited()) {
            ImageLoaderConfiguration config = getImgConfig(c);
            if (config != null) {
                loader.init(config);
            }
        }
        return loader;
    }

    /**
     * default option
     * 得到默认的option 采用imageloader的 imageScaleType;
     * imagescalType imageloader会默认压缩图片
     *
     * @param errorBgRes
     * @param defaultBgRes
     * @return
     */
    private static DisplayImageOptions getImageOptionsPress(int errorBgRes,
                                                            int defaultBgRes) {
        DisplayImageOptions.Builder builder = getDisplayImageOptionsBuilder(errorBgRes,
                defaultBgRes);
        return null == builder ? null : builder.build();
    }

    private static DisplayImageOptions.Builder getDisplayImageOptionsBuilder(int errorBgRes,
                                                                             int defaultBgRes) {
        return new DisplayImageOptions.Builder()
                .showImageOnLoading(
                        defaultBgRes == 0 ? getImageDefaultBG() : defaultBgRes)
                .showImageForEmptyUri(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .showImageOnFail(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY);

    }

    public static DisplayImageOptions.Builder createFullImageOptions(int errorBgRes,
                                                                     int defaultBgRes) {
        return new DisplayImageOptions.Builder()
                .showImageOnLoading(
                        defaultBgRes == 0 ? getImageDefaultBG() : defaultBgRes)
                .showImageForEmptyUri(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .showImageOnFail(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY);

    }

    public static DisplayImageOptions.Builder createLocalImageOptions(int errorBgRes,
                                                                      int defaultBgRes) {
        return new DisplayImageOptions.Builder()
                .showImageOnLoading(
                        defaultBgRes == 0 ? getImageDefaultBG() : defaultBgRes)
                .showImageForEmptyUri(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .showImageOnFail(
                        errorBgRes == 0 ? getImageErrorBG() : errorBgRes)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .delayBeforeLoading(50)
                .cacheInMemory(false).cacheOnDisk(false).considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY);

    }

    public static ImageLoaderConfiguration getImgConfig(Context context) {
        if (context != null) {
            DisplayImageOptions.Builder defaultOptions = new DisplayImageOptions.Builder()
                    .showImageOnLoading(getImageDefaultBG())
                    .showImageForEmptyUri(getImageErrorBG())
                    .showImageOnFail(getImageErrorBG())
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                    .imageScaleType(ImageScaleType.EXACTLY);
            int memoryCacheSize = (int)(Runtime.getRuntime().maxMemory()/8);
            Log.d("imageloader","memoryCacheSize-->"+memoryCacheSize);
            File file = new File(FileConstants.getImageDirPath(context.getApplicationContext()));
            if (!file.exists()){
                file.mkdir();
            }
            LruMemoryCache memoryCache = new LruMemoryCache(memoryCacheSize);
            return new ImageLoaderConfiguration.Builder(context)
                    .threadPoolSize(3)
                    .threadPriority(Thread.NORM_PRIORITY - 2)
                    .diskCache(new UnlimitedDiskCache(file))
                    .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                    .diskCacheSize(50 * 1024 * 1024)
                    .diskCacheFileCount(100)
                    .diskCacheExtraOptions(480, 320, null)
                    .memoryCache(memoryCache)
                    .defaultDisplayImageOptions(defaultOptions.build())
                    .memoryCacheSize(memoryCacheSize)
                    .tasksProcessingOrder(QueueProcessingType.LIFO)
                    .writeDebugLogs() // Remove for release app
                    .build();
        }

        return null;
    }

    public static void loadImageListener(ImageLoadingListener listener,
                                         String url, DisplayImageOptions options, Context c) {
        ImageLoader loader = getImageLoader(c);
        if (options != null)
            loader.loadImage(url, options, listener);
        else
            loader.loadImage(url, listener);
    }

    /**
     * 加载网络圆形图片
     *
     * @param c
     * @param iv
     * @param imageUrl
     * @param errorBgRes
     * @param defaultBgRes
     */
    public static void loadCircleImage(Context c, ImageView iv, String imageUrl,
                                       int errorBgRes, int defaultBgRes) {
        DisplayImageOptions.Builder builder = getDisplayImageOptionsBuilder(errorBgRes, defaultBgRes);
        if (null == builder) {
            return;
        }
        builder.displayer(new RoundedBitmapDisplayer(1000));
        loadImage(c, iv, imageUrl, builder.build());
    }

    public static void loadImageListener(ImageLoadingListener listener,
                                         String url, Context c) {
        loadImageListener(listener, url, null, c);
    }

    /**
     * 异步加载本地SD卡图片
     *
     * @param imgView
     * @param path
     */
    public static void loadLocalImage(final ImageView imgView, final String path) {
        loadImage(imgView.getContext(), imgView, Scheme.FILE.wrap(path), getDisplayImageOptionsBuilder(0,0).build());
    }

    /**
     * 异步加载本地图片(圆形)
     *
     * @param imgView
     * @param path
     */
    public static void loadLocalCircleImage(ImageView imgView, final String path) {
        if (null == imgView) {
            return;
        }
        if (TextUtils.isEmpty(path)) {
            return;
        }
        DisplayImageOptions.Builder builder = createLocalImageOptions(0, 0);
        if (null == builder) {
            return;
        }
        builder.displayer(new RoundedBitmapDisplayer(1000));
        ImageLoader loader = getImageLoader(imgView.getContext());
        loader.displayImage(Scheme.FILE.wrap(path), imgView, builder.build());
    }

    public static int getImageDefaultBG() {
        return R.drawable.bg_im_img;
    }

    public static int getImageErrorBG() {
        return R.drawable.bg_im_img;
    }

    public static int getImageEmpty() {
        return R.drawable.bg_im_img;
    }
}
